package com.checkCode.strategy;

import com.checkCode.constants.CheckCodeType;
import com.checkCode.entity.dto.CheckCodeResultDto;
import com.checkCode.entity.vo.CheckCodeParamsVo;
import com.checkCode.service.serviceImpl.CheckCodeServiceImpl;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 大忽悠
 * @create 2023/2/9 21:15
 */
@Component
public class PicCodeGeneratorStrategy implements CodeGeneratorStrategy{
    @Autowired
    private DefaultKaptcha kaptcha;
    /**
     * 是否支持当前类型的验证码生成
     *
     * @param checkCodeParamsVo
     */
    @Override
    public Boolean support(CheckCodeParamsVo checkCodeParamsVo) {
        return Objects.equals(checkCodeParamsVo.getCheckCodeType(), CheckCodeType.PIC_CODE);
    }

    /**
     * 生成验证码
     *  @param checkCodeParamsVo
     * @param code
     */
    @Override
    public CheckCodeResultDto generate(CheckCodeParamsVo checkCodeParamsVo, CheckCodeServiceImpl.CodeInfo code) {
        String base64CodeImg = createPic(code.getCode());
        return CheckCodeResultDto.builder().key(code.getCodeKey()).aliasing(base64CodeImg).build();
    }

    private String createPic(String code) {
        // 生成图片验证码
        ByteArrayOutputStream outputStream = null;
        BufferedImage image = kaptcha.createImage(code);

        outputStream = new ByteArrayOutputStream();
        String imgBase64Encoder = null;
        try {
            // 对字节数组Base64编码
            ImageIO.write(image, "png", outputStream);
            imgBase64Encoder = "data:image/png;base64," + Base64Utils.encodeToString(outputStream.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return imgBase64Encoder;
    }
}
